package interceptor01.demo.handler;

import com.alibaba.fastjson.JSON;
import interceptor01.demo.po.ResultPo;
import interceptor01.demo.po.UserInfoPo;
import interceptor01.demo.po.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行controller方法（handler）之前执行
        /**
         * 1、需要判断，请求的接口路径是否为HandlerMethod(controller方法)
         * 2、判断token是否为空，如果为空，未登录
         * 3、如果登录，获取token的值
         * 4、如果登录成功 放行1
         * */
        if(!(handler instanceof HandlerMethod)){
            //如果不是controller方法放行，在前后端分离架构中不存在
            return true;
        }

        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            ResultPo resultPo = new ResultPo();
            resultPo.setCode(9999);
            resultPo.setMsg("未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(resultPo));
            return false;
        }

        //根据token获取用户信息

        UserInfoPo userInfoPo = new UserInfoPo();
        userInfoPo.setAge(12);
        userInfoPo.setName("zhangsan");

        UserThreadLocal.put(userInfoPo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //使用完之后需要remove掉，否则会出现内存泄露的问题
        UserThreadLocal.remove();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
